package com.liang.utils.qniuyun;


import com.liang.utils.DateUtils;
import com.qiniu.common.QiniuException;
import com.qiniu.http.Response;
import com.qiniu.storage.BucketManager;
import com.qiniu.storage.Configuration;
import com.qiniu.storage.Region;
import com.qiniu.storage.UploadManager;
import com.qiniu.storage.model.FileInfo;
import com.qiniu.util.Auth;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.PropertySource;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.util.Objects;
import java.util.UUID;


@PropertySource(value = "classpath:thirdparty.properties")
@Service
public class QiniuOSSServiceImpl implements QiniuOSSService {

    @Autowired
    private Auth auth;

    @Autowired
    private UploadManager uploadManager;

    @Autowired
    private BucketManager bucketManager;


    @Value("${qiniu.path}")
    private String path;       // 域名
    @Value("${qiniu.documentname1}")
    private String documentName;   // 空间里的文件夹
    @Value("${qiniu.file.allow}")
    private String[] allowed; //图片允许的扩展名
    @Value("${qiniu.bucketName}")
    private String bucketName;   // 存储空间

    @Override
    public String uploadFile(MultipartFile file)  {
        //构造一个带指定 Region 对象的配置类
        Configuration cfg = new Configuration(Region.huabei());
        String key = DateUtils.getTodayDate() + UUID.randomUUID().toString();
//        System.out.println("文件上传....");

        try {
            String upToken = auth.uploadToken(bucketName);
            try {
                Response response = uploadManager.put(file.getInputStream(),documentName + key,upToken,null, null);
                //解析上传成功的结果
                if (response.statusCode==200){
//                    System.out.println("上传成功");
                    return key;
                }else {
//                    System.out.println("上传失败");
                    return null;
                }
            } catch (QiniuException ex) {
                Response r = ex.response;
//                System.err.println(r.toString());
//                System.out.println("上传失败");
                try {
                    System.err.println(r.bodyString());
                } catch (QiniuException ex2) {
                    //ignore
                }
            }
        } catch (Exception ex) {
            //ignore
        }

        return null;
    }

    @Override
    public Boolean deleteFile(String key) throws RuntimeException {
        key = documentName + key;
        if (Objects.isNull(checkFile(key))) {
            return true;
        } else {
            try {
                bucketManager.delete(bucketName,key);
                return true;
            } catch (QiniuException e) {
                return false;

            }
        }



    }

    @Override
    public FileInfo checkFile(String key) {
        FileInfo fileInfo = null;
        try {
            fileInfo = bucketManager.stat(bucketName, key);
        } catch (QiniuException ignored) {
        }
        return fileInfo;
    }

    @Override
    public String getFileAskingPath(String filePath) {
        return path + "/" + filePath;
    }

    /**
     * 生成唯一图片名称
     *
     * @param fileName 原文件名
     * @return 云服务器fileName
     */
    private static String getRandomImgName(String fileName) throws IllegalArgumentException {
        int index = fileName.lastIndexOf(".");

        if (fileName.isEmpty() || index == -1) {
            throw new IllegalArgumentException();
        }
        // 获取文件后缀
        String suffix = fileName.substring(index).toLowerCase();
        // 生成UUID
        String uuid = UUID.randomUUID().toString().replaceAll("-", "");
        // 拼接新的名称
        return uuid + suffix;
    }

    /**
     * 判断文件是否被允许上传
     *
     * @param fileName 文件名
     * @return 允许true, 否则false
     */
    private boolean isFileAllowed(String fileName) {
        // 获取后缀名
        String suffixName = fileName.substring(fileName.lastIndexOf(".") + 1).toLowerCase();
        for (String allow : allowed) {
            if (allow.equals(suffixName)) {
                return true;
            }
        }
        return false;
    }
}
